package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.dindang.propertyfee.R;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.Cn2Spell;
import com.dindang.propertyfee.app.utils.NodesTreeUtils;
import com.dindang.propertyfee.app.utils.TimeComparisonUtils;
import com.dindang.propertyfee.mvp.contract.FeeAdvancedSearchContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.Build;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.OwnerSearchViewAdapter;
import com.dindang.propertyfee.mvp.ui.widget.BuildSelectDialog;
import com.dindang.propertyfee.mvp.ui.widget.CommunitySelectDialog;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.utils.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class FeeAdvancedSearchPresenter extends BasePresenter<FeeAdvancedSearchContract.Model, FeeAdvancedSearchContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    //文件名称
    private final static String CityFileName = "community2.json";
    private boolean isLoadCommunity = false;
    private String HISTORY_SP_KEY = "XIAOQUHISTORY";

    private TimePickerView pvCustomTime;
    Calendar selectedDate = Calendar.getInstance();//系统当前时间
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    boolean isSearch = false;

    private int limit = 10;
    private PropertyCharge.RecentBillParam mRecentBillParam = new PropertyCharge.RecentBillParam(limit);
    private Build.BuildParam mBuildParam = new Build.BuildParam("","","");
    private Build.NodesParam mNodesParam = new Build.NodesParam();

    @Inject
    public FeeAdvancedSearchPresenter(FeeAdvancedSearchContract.Model model, FeeAdvancedSearchContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        initParamStartAndEndDate();
        initListener();
    }

    private void initParamStartAndEndDate() {
        mRecentBillParam.startDate = TimeComparisonUtils.dateTString2(startDate.getTime());
        mRecentBillParam.endDate = TimeComparisonUtils.dateTString2(endDate.getTime());
    }

    private void initListener() {

        mRootView.getTvDataStart().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogStartDateTime(mRootView.getTvDataStart(), "选择开始日期");
//                initTimePicker();
            }
        });

        mRootView.getTvDataEnd().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogEndDateTime(mRootView.getTvDataEnd(), "选择结束日期");
            }
        });

        mRootView.getTvVillageName().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogVillageName();
            }
        });

    }

    /**
     * 时间选择开始
     * @param tvData
     * @param title
     */
    private void dialogStartDateTime(TextView tvData, String title) {
        Calendar startStartDate = Calendar.getInstance();
        startStartDate.set(selectedDate.get(Calendar.YEAR) - 1, 0, 1);

        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(mRootView.getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                startDate.setTime(date);
                tvData.setText(TimeComparisonUtils.dateTMDString(date));
                mRecentBillParam.startDate = TimeComparisonUtils.dateTString2(date);
            }
        })
        .setDate(startDate)
        .setRangDate(startStartDate, endDate)
        .setLayoutRes(R.layout.propertyfee_pickerview_custom_time, new CustomListener() {

            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.propertyfee_tv_finish);
                final TextView tvTitle = v.findViewById(R.id.propertyfee_tv_title);
                tvTitle.setText(title);
                ImageView ivCancel = v.findViewById(R.id.propertyfee_iv_dialog_close);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomTime.returnData();
                        pvCustomTime.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomTime.dismiss();
                    }
                });
            }
        })
        .setContentTextSize(16)
        .setType(new boolean[]{true, true, true, false, false, false})
        .setLabel("年", "月", "日", "时", "分", "秒")
        .setLineSpacingMultiplier(3f)
        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
        .setDividerColor(0xFFd1d1d1)
        .build();

        pvCustomTime.show();
    }

    /**
     * 时间选择结束
     * @param tvData
     * @param title
     */
    private void dialogEndDateTime(TextView tvData, String title) {
        Calendar endEndDate = Calendar.getInstance();
        endEndDate.set(selectedDate.get(Calendar.YEAR) + 1, 11, 31);

        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(mRootView.getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                endDate.setTime(date);
                tvData.setText(TimeComparisonUtils.dateTMDString(date));
                mRecentBillParam.endDate = TimeComparisonUtils.dateTString2(date);
            }
        })
        .setDate(endDate)
        .setRangDate(startDate, endEndDate)
        .setLayoutRes(R.layout.propertyfee_pickerview_custom_time, new CustomListener() {

            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.propertyfee_tv_finish);
                final TextView tvTitle = v.findViewById(R.id.propertyfee_tv_title);
                tvTitle.setText(title);
                ImageView ivCancel = v.findViewById(R.id.propertyfee_iv_dialog_close);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomTime.returnData();
                        pvCustomTime.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomTime.dismiss();
                    }
                });
            }
        })
        .setContentTextSize(16)
        .setType(new boolean[]{true, true, true, false, false, false})
        .setLabel("年", "月", "日", "时", "分", "秒")
        .setLineSpacingMultiplier(3f)
        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
        .setDividerColor(0xFFd1d1d1)
        .build();

        pvCustomTime.show();
    }

    CommunitySelectDialog.Builder mCommunitySelectDialog;
    /**
     * 小区选择
     */
    private void dialogVillageName(){
        if(mCommunitySelectDialog != null){
            mCommunitySelectDialog.show();
            return;
        }else {
            mCommunitySelectDialog = new CommunitySelectDialog.Builder(mRootView.getActivity());
            mCommunitySelectDialog.setTitle("请选择小区")
            .setProperty(new CommunitySelectDialog.OnCommunityListener() {
                @Override
                public void onClick(Build.Building cityEntity) {
                    mNodesParam.setNodesParam(BaseAppConst.accountInfo.getCorpId(), cityEntity.id);
                    dialogBuild(cityEntity);
                }

                @Override
                public void onSure(Build.Building building) {
                    mRecentBillParam.bid = building.id;// 小区id
                    mRecentBillParam.nodeValue = "";// 节点值
                    mRootView.getTvVillageName().setText(building.name);

                    mCommunitySelectDialog.dismiss();
                }
            })
            .create()
            .show();
        }

        queryRecentBill();
    }

    protected List<Build.Building> hotCityList = new ArrayList<>();
    protected List<Build.Building> totalCityList = new ArrayList<>();
    protected List<Build.Building> curCityList = new ArrayList<>();
    private List<String> initialList = new ArrayList<>();
    private String[] keys = {};

    /**
     * 查询权限小区
     */
    private void queryRecentBill(){

        hotCityList.clear();
        String historyKeyword = SharedPreferencesUtils.getParam(mApplication, HISTORY_SP_KEY, "").toString();
        if(!TextUtils.isEmpty(historyKeyword)){
            hotCityList = JSON.parseArray(historyKeyword, Build.Building.class);
        }

        if(null != BaseAppConst.accountInfo){
            mBuildParam.corpId = BaseAppConst.accountInfo.getCorpId();
            mBuildParam.isAdmin = BaseAppConst.accountInfo.getIsAdmin();
            mBuildParam.cId = BaseAppConst.accountInfo.getUserId()+"";
        }else{
            ARouter.getInstance().build("/activity/LoginActivity").navigation(mAppManager.getCurrentActivity(), AppConst.IntentRequstCode.ACTIVITY_LOGIN);
        }
        mModel.findBuilding(mBuildParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<List<Build.Building>>>(mErrorHandler) {
            @Override
            public void onError(Throwable t) {
                super.onError(t);
                Toast.makeText(mRootView.getActivity(),t.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(BaseResponse<List<Build.Building>> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }

                if(isLoadCommunity){
                    return;
                }
                isLoadCommunity = true;

                totalCityList.clear();
                initialList.clear();

                totalCityList.add(new Build.Building("历史记录", "0"));
                for (Build.Building building : response.getData()) {
                    building.pinyin = Cn2Spell.getPinYin(building.name);
                    building.key = building.pinyin.substring(0, 1).toUpperCase();
                    if(!initialList.contains(building.key)){
                        initialList.add(building.key);
                    }
                    totalCityList.add(building);
                }
                keys=initialList.toArray(new String[initialList.size()]);
                mCommunitySelectDialog.setInitial(keys);
                mCommunitySelectDialog.updateData(hotCityList, totalCityList, curCityList);
            }
        });
    }

    BuildSelectDialog.Builder mBuildSelectDialog;
    /**
     * 楼栋选择
     */
    private void dialogBuild(Build.Building buildingParent) {
        if(mBuildSelectDialog != null){
            mBuildSelectDialog.show();
        }else {
            mBuildSelectDialog = new BuildSelectDialog.Builder(mRootView.getActivity());
            mBuildSelectDialog.setTitle("请选择楼栋")
            .setBuildingParent(buildingParent)
            .setProperty(new BuildSelectDialog.OnBuildListener() {
                @Override
                public void onSearchClick(Build.Building building, List<Build.Nodes> nodesList) {
                    if(nodesList.size() > 0){
                        String nodeValue = NodesTreeUtils.getChildsId(nodesList);
//                        LogUtils.debugInfo("buildingParent", nodeValue);
                        mRecentBillParam.bid = building.id;// 小区id
                        mRecentBillParam.nodeValue = nodeValue;// 节点值
                        mRootView.getTvVillageName().setText(building.name);

                        mCommunitySelectDialog.dismiss();
                        mBuildSelectDialog.dismiss();
                    }
                }

                @Override
                public void onClick(Build.Nodes nodes) {
                    mCNodevaluesMap.put("cNodevalue" + level, nodes.text);
                    queryNodes(nodes.mId);
                }

                @Override
                public void onBack() {
                    mCNodevaluesMap.remove("cNodevalue" + level);
                    level--;
                    mBuildSelectDialog.upLevel();
                }
            })
            .create()
            .show();
        }
        mCNodevaluesMap.clear();
        level = 0;
        mCNodevaluesMap.put("cNodevalue" + level, buildingParent.name);
        queryNodes(0);
    }

    private int level = 0;//当前第几级
    private Map<String, String> mCNodevaluesMap = new HashMap<>();//cNodevalue1, cNodevalue2, cNodevalue3, cNodevalue4......文档查询楼栋结构用
    /**
     * 查询楼栋结构
     */
    private void queryNodes(int pid){
        mBuildSelectDialog.load();
        mModel.queryNodes(mNodesParam, mCNodevaluesMap)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<List<Build.Nodes>>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<List<Build.Nodes>> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }

                for (Build.Nodes nodes : response.getData()){
                    nodes.mId = nodes.id + nodes.lv;
                    nodes.mPid = pid;
                }

                mBuildSelectDialog.downLevel(response.getData(), "cNodevalue", level);
                level++;
            }
        });
    }

    /**
     * 搜索用
     */
    public void toSearch() {
//        if(mTotals.size() == 0){
//            initTotal();
//            mAdapter = new OwnerSearchViewAdapter(mTotals, new OwnerSearchViewAdapter.OnOwnerSearchListener() {
//                @Override
//                public void onClick(int position) {
//                    Intent intent = new Intent(mRootView.getActivity(), ReceivableDetailActivity.class);
//                    mRootView.getActivity().startActivity(intent);
//                }
//            });
//            mRootView.getListview().setAdapter(mAdapter);
//            mAdapter.notifyDataSetChanged();
//        }
//        mRootView.getListview().setVisibility(View.VISIBLE);
//        isSearch = true;

        ARouter.getInstance().build("/propertyfee/activity/FeeList2Activity")
                .withString(AppConst.DUE_TO, AppConst.DUE_TO_TITLE_ADVANCED)
                .withSerializable(AppConst.PARAM_DATA, mRecentBillParam)
                .navigation();

    }

    private List<PropertyCharge.Total> mTotals = new ArrayList<>();//没后台 本地测试数据
    private OwnerSearchViewAdapter mAdapter;
    /**
     * 初始化本地搜索数据
     */
    private void initTotal() {
        for (int i = 1; i <= 20; i++) {
            PropertyCharge.Total total = new PropertyCharge.Total(
                    "丁当社区1幢1单元101室-" + i,
                    i + 100,
                    "张" + i,
                    "1866871993" + i);
            mTotals.add(total);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.pvCustomTime = null;
        this.mCommunitySelectDialog = null;
        this.hotCityList = null;
        this.totalCityList = null;
        this.curCityList = null;
        this.initialList = null;
        this.keys = null;

        this.mBuildSelectDialog = null;

        this.mAdapter = null;
        this.mTotals = null;

        this.mRecentBillParam = null;
        this.mBuildParam = null;
        this.mNodesParam = null;

        this.mCNodevaluesMap = null;
    }

    public void finish() {
        mRootView.getActivity().finish();
//        if(isSearch){
//            isSearch = false;
//            mRootView.getListview().setVisibility(View.GONE);
//        }else{
//            mRootView.getActivity().finish();
//        }
    }
}
